class SignController < ApplicationController
  
  verify :method => :post, :only => [:create_user, :sign_in_from_welcome],
         :redirect_to => {:action => :sign_in}
  
  layout 'account'
  
  def sign_in
    @title = 'Login'
    if request.post?
      @recap, @user = sign_in_babaru(:need_recaptcha => true)
      if @user && @recap
        login_success(@user)
      elsif @user && !@recap
        render :action => 'sign_in'
      else
        flash[:notice] = "Invalid login/password combination."
      end
    end
  end
  
  def sign_in_from_welcome
    @recap, @user = sign_in_babaru(:need_recaptcha => false)
    if @user
      login_success(@user)
    else
      flash[:notice] = "Invalid login/password combination."
      redirect_to :action => 'sign_in'
    end
  end
  
  # Sign out from system
  def sign_out
    session[:user_id] = nil
    unless session[:origin_url]
      redirect_to welcome_url and return
    end
    redirect_to session[:origin_url] and return
    
  end
  
  protected 
  
  def sign_in_babaru(options={})
    default_options = {:need_recaptcha => true}
    options = default_options.merge(options)
    
    session[:user_id] = nil
    @user = User.authenticate(params[:login], params[:password])
    if @user
      if options[:need_recaptcha]
        if validate_recap(params, @user.errors)
          return [true, @user]
        else
          return [false, @user]
        end
      else
        return [false, @user]
      end
    else
      return [false, nil]
    end
  end
  
  def login_success(user)
    flash[:notice] = nil
    session[:user_id] = @user.id
    if session[:origin_url]
      redirect_to session[:origin_url] and return
    else
      redirect_to index_url(:screen_name => @user.lough.screen_name) and return
    end
  end
end
